<template>
  <div class="app-container">
    <div class="filter-container top">
      <el-input v-if="isAdmin" v-model="listQuery.college" placeholder="学院名" style="width: 200px; margin-right: 20px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"
      />
      <el-button v-if="isAdmin" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-if="isAdmin"
                 class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                 @click="handleDownload"
      >
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" prop="index" label="序号" align="center" width="80"/>

      <el-table-column label="账号" min-width="150px" prop="account">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.account }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户昵称" min-width="150px" prop="username">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="学院" min-width="150px" prop="college">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.college }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户身份" min-width="150px" prop="identity">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.identity | parseUserIdentity }}</span>
        </template>
      </el-table-column>

      <el-table-column label="真实姓名" min-width="150px" prop="realName">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.realName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="电话" min-width="150px" prop="tel">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.tel }}</span>
        </template>
      </el-table-column>

      <el-table-column label="QQ" min-width="150px" prop="tel">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.QQ }}</span>
        </template>
      </el-table-column>

      <el-table-column label="wechat" min-width="150px" prop="tel">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.wechat }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户类型" min-width="150px" prop="userType">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.userType | parseUserType }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户状态" min-width="150px" prop="active">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.active"
            :active-value="active[0].id"
            :inactive-value="active[1].id"
            :active-text="active[0].des"
            :inactive-text="active[1].des"
            @change="userStatusChange($event, row.id)"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="!isAdmin || checkSelf(row.id)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="resetPwd(row.id)">
            重置密码
          </el-button>
          <el-button v-if="isAdmin && !checkSelf(row.id)" size="mini" type="danger"
                     @click="handleDelete(row,$index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="temp.account"/>
        </el-form-item>

        <el-form-item label="用户昵称" prop="username">
          <el-input v-model="temp.username"/>
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="dialogStatus === 'create'">
          <el-input v-model="temp.password"/>
        </el-form-item>

        <el-form-item label="所属学院" prop="collegeId">
          <el-select v-model="temp.collegeId" placeholder="请选择所在学院" clearable class="filter-item">
            <el-option v-for="item in college" :key="item.id" :label="item.college" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="用户身份" prop="identity">
          <el-select v-model="temp.identity" placeholder="请选择用户类型" clearable class="filter-item">
            <el-option v-for="item in identity" :key="item.code" :label="item.des" :value="item.code"/>
          </el-select>
        </el-form-item>

        <el-form-item label="用户类型" prop="userType" v-show="isAdmin">
          <el-select v-model="temp.userType" placeholder="请选择用户类型" clearable class="filter-item">
            <el-option v-for="item in userType" :key="item.code" :label="item.des" :value="item.code"/>
          </el-select>
        </el-form-item>

        <el-form-item label="电话" prop="tel">
          <el-input v-model="temp.tel"/>
        </el-form-item>

        <el-form-item label="QQ" prop="QQ">
          <el-input v-model="temp.QQ"/>
        </el-form-item>

        <el-form-item label="微信" prop="wechat">
          <el-input v-model="temp.wechat"/>
        </el-form-item>

        <el-form-item label="用户状态" prop="active" v-if="isAdmin">
          <el-select v-model="temp.active" placeholder="请选择用户状态" clearable class="filter-item">
            <el-option v-for="item in active" :key="item.id" :label="item.des" :value="item.id"/>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!--  修改密码对话框  -->
    <el-dialog title="重置密码" :visible.sync="resetPwdFormVisible">
      <el-form ref="resetPwd" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="新密码" prop="password">
          <el-input v-model="temp.password"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetPwdFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="doResetPwd">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { collegeRestfull } from '@/api/college'
import { userRestfull, changeUserStatus, resetPassword } from '@/api/user'
import { mapGetters } from 'vuex'
import { UserType } from '@/utils/auth'
import waves from '@/directive/waves' // waves directive
import { parseTime, parseUserIdentity, parseUserType } from '@/utils'
import Pagination from '@/components/Pagination'
import { goodsTypeRestfull } from '@/api/goods-type'
import de from 'element-ui/src/locale/lang/de'
import user from '@/store/modules/user' // secondary package based on el-pagination

export default {
  name: 'User',
  components: { Pagination },
  directives: { waves },
  filters: {
    parseTime,
    parseUserIdentity,
    parseUserType
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        college: undefined
      },
      temp: {
        id: undefined,
        collegeId: undefined,
        account: undefined,
        password: undefined,
        identity: undefined,
        realName: undefined,
        tel: undefined,
        userType: undefined,
        username: undefined,
        QQ: undefined,
        wechat: undefined,
        active: 0
      },
      active: [
        {
          id: 0,
          des: '启用'
        }, {
          id: 1,
          des: '禁用'
        }
      ],
      dialogFormVisible: false,
      resetPwdFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加用户'
      },
      rules: {
        account: [{ required: true, message: '账号不能为空', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'change' }],
        userType: [{ required: true, message: '用户类型不能为空', trigger: 'change' }]
      },
      downloadLoading: false,
      college: undefined,
      identity: {
        student: {
          des: '学生',
          code: 0
        },
        teacher: {
          des: '老师',
          code: 1
        }
      },
      userType: {
        student: {
          des: '普通用户',
          code: 0
        },
        teacher: {
          des: '管理员',
          code: 1
        }
      }
    }
  },
  computed: {
    ...mapGetters(['roles', 'userId']),
    isAdmin() {
      return this.roles.includes(UserType.SUPER_ADMIN.des) ||
        this.roles.includes(UserType.ADMIN.des)
    }
  },
  created() {
    this.getList()
    this.getAllCollege()
  },
  methods: {
    getList() {
      this.listLoading = true
      userRestfull.fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getAllCollege() {
      collegeRestfull.fetchAll().then(response => {
        this.college = response.data
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        collegeId: undefined,
        account: undefined,
        identity: undefined,
        realName: undefined,
        tel: undefined,
        userType: undefined,
        username: undefined,
        QQ: undefined,
        wechat: undefined,
        active: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          userRestfull.createData(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.total += 1
            this.$notify({
              title: '成功',
              message: '用户添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          userRestfull.updateData(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '用户信息更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userRestfull.removeData(row.id).then(() => {
          this.list.splice(index, 1)
          this.total -= 1
          this.$notify({
            title: '成功',
            message: '用户信息已删除',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      // import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const data = this.formatJson(filterVal)
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: 'table-list'
      //   })
      //   this.downloadLoading = false
      // })
      import('@/utils/excel-export').then(exportExcel => {
        const tHeader = {
          id: 'id',
          college: '学院'
        }
        exportExcel.exportExcel(tHeader, this.list, 'college')
      })
      this.downloadLoading = false
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    userStatusChange(active, id) {
      changeUserStatus({ id, active }).then(_ => {
        this.$notify({
          title: '成功',
          message: '用户状态修改成功',
          type: 'success',
          duration: 2000
        })
      }).catch(_ => {
        this.$notify({
          title: '失败',
          message: '用户状态修改失败',
          type: 'error',
          duration: 2000
        })
      })
    },
    isUserActive(active) {
      let rs = this.active[active]
      return rs ? rs.flag : false
    },
    checkSelf(id) {
      return id === this.userId
    },
    resetPwd(id) {
      this.temp.id = id
      this.resetPwdFormVisible = true
      this.$nextTick(() => {
        this.$refs['resetPwd'].clearValidate()
      })
    },
    doResetPwd() {
      this.$refs['resetPwd'].validate((valid) => {
        if (valid) {
          resetPassword({ id: this.temp.id, password: this.temp.password }).then(() => {
            this.resetPwdFormVisible = false
            this.$notify({
              title: '成功',
              message: '密码重置成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button--mini {
  padding: 7px 10px;
  min-width: 56px;
}

.top {
  margin-bottom: 20px;
}
</style>
